package com.cwj.socket;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author wujie.chen
 * 2021/10/14 17:31
 */
public class Client {
    public static void main(String[] args) throws IOException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        while(true){
            Socket socket = new Socket("localhost", 8888);
            socket.setKeepAlive(true);
            Scanner scanner = new Scanner(System.in);
            String message = scanner.nextLine();
            OutputStream outputStream = socket.getOutputStream();
            PrintWriter printWriter = new PrintWriter(outputStream);
            printWriter.write(message);
            System.out.println("客户端消息: " + message);
            printWriter.flush();
            socket.shutdownOutput();

            executorService.execute(new ResponseHandler(socket));
        }
    }

    public static class ResponseHandler implements Runnable{
        private final Socket socket;

        public ResponseHandler(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            try {
                InputStream inputStream = socket.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                String info;
                StringBuilder sb = new StringBuilder();
                while((info = bufferedReader.readLine())!=null){
                    sb.append(info);
                }
                System.out.println("服务端消息：" + sb.toString());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
